const app = getApp()
// console.log(app);
const toast = (title,reject) => {
  wx.showToast({
    title,
    icon: 'none',
  })
  reject(title)
}

const request = (url,data = {},method = "GET") => {
  // console.log(data);
  return new Promise((resolve,reject) => {
    wx.showLoading({title: '加载中',})
    let msg = ""
    wx.request({
      url:app.globalData.baseUrl + url,
      data,
      header: {
        Authorization: "Bearer " + wx.getStorageSync('access_token') || ""
      },
      method,
      success: (res) => {
        if(res.statusCode < 400)   resolve(res.data)
        //服务器不理解请求的语法
        if(res.statusCode == 400) msg = res.data.message

        //（未授权）请求要求身份验证。
        if(res.statusCode == 401){
          msg = "请先登录"
        }

        //（禁止）无权限, 服务器拒绝请求。
        if(res.statusCode == 403) msg = "权限不够"

        //（未找到） 服务器找不到请求的资源
        if(res.statusCode == 404) msg = "找不到相应资源"

        //（超时） 请求超时
        if(res.statusCode == 408) msg = "连接超时,请稍后再试"

        //	（验证错误） 请求参数未通过验证
        if(res.statusCode == 422) msg = "请求参数未通过验证"

        //（被限制）请求次数过多
        if(res.statusCode == 429)  msg = "连续请求次数太多,请稍后再试"
        if(msg)   toast(msg,reject)

      },
      fail: (err) => {
         reject(err)
      },
      complete () {
        wx.hideLoading()
        // console.log("1111");
      },
    })
  })
}

const Ajax =  {
  get : (url,data = {}) => request(url,data,"GET"),
  post : (url,data = {}) => request(url,data,"POST"),
  put : (url,data = {}) => request(url,data,"PUT"),
  patch : (url,data ={}) =>{
    data = {
      ...data,
      _method:"PATCH"
    }
    request(url,data,"POST")
  } ,
  delete : (url,data = {}) => request(url,data,"DELETE"),
}

export {
  request,
  Ajax
}